package com.ruoyi.factory.bom.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.factory.bom.domain.BomCost;
import com.ruoyi.factory.bom.domain.BomTreeSelect;
import com.ruoyi.factory.bom.mapper.BomCostMapper;
import com.ruoyi.factory.bom.service.IBomCostService;
import com.ruoyi.factory.bom.service.IUpdateMaterialPriceService;
import com.ruoyi.factory.common.domain.AjaxBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * bom模型Service业务层处理
 *
 * @author ruoyi
 * @date 2022-10-30
 */
@Service
public class BomCostServiceImpl implements IBomCostService
{
    @Autowired
    private BomCostMapper bomCostMapper;

    @Autowired
    private IUpdateMaterialPriceService updateMaterialPriceService;

    @Autowired
    IUpdateMaterialPriceService upMaterPriceService;

    /**
     * 查询bom模型
     *
     * @param id bom模型主键
     * @return bom模型
     */
    @Override
    public BomCost selectBomCostById(String id)
    {
        return bomCostMapper.selectBomCostById(id);
    }

    /**
     * 查询bom模型列表
     *
     * @param bomCost bom模型
     * @return bom模型
     */
    @Override
    public List<BomCost> selectBomCostList(BomCost bomCost)
    {
        return bomCostMapper.selectBomCostList(bomCost);
    }

    @Override
    public List<BomTreeSelect> buildBomCostTreeSelect(List<BomCost> bomCosts)
    {
        List<BomCost> bomCostTrees = buildBomCostTree(bomCosts);
        return bomCostTrees.stream().map(BomTreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public List<BomCost> buildBomCostTreeSelect2(List<BomCost> bomCosts)
    {
        List<BomCost> bomCostTrees = buildBomCostTree(bomCosts);
        return bomCostTrees;
    }

    /**
     * 构建前端所需要树结构
     *
     * @param
     * @return 树结构列表
     */
    @Override
    public List<BomCost> buildBomCostTree(List<BomCost> bomCosts)
    {
        List<BomCost> returnList = new ArrayList<BomCost>();
        List<String> tempList = new ArrayList<String>();
        for (BomCost bomCost : bomCosts) {
            tempList.add(bomCost.getPartId());
        }
        for (BomCost bomCost : bomCosts) {
            if (!tempList.contains(bomCost.getParentId()))
            {
                recursionFn(bomCosts, bomCost);
                returnList.add(bomCost);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = bomCosts;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<BomCost> list, BomCost t)
    {
        // 得到子节点列表
        List<BomCost> childList = getChildList(list, t);
        t.setChildren(childList);
        for (BomCost tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }
    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<BomCost> list, BomCost t)
    {
        return getChildList(list, t).size() > 0;
    }
    /**
     * 得到子节点列表
     */
    private List<BomCost> getChildList(List<BomCost> list, BomCost t)
    {
        List<BomCost> tlist = new ArrayList<BomCost>();
        Iterator<BomCost> it = list.iterator();
        while (it.hasNext())
        {
            BomCost n = (BomCost) it.next();
//            String partId = t.getPartId();
//            String parentId = n.getParentId();
//            boolean equals = partId.equals(parentId);
//            System.out.println("是否相等"+equals);
//            System.out.println("n---"+parentId);
//            System.out.println("t---"+partId);
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().equals(t.getPartId()) && n.getBomName().equals(t.getBomName()) && n.getBomVar().equals(t.getBomVar()))
            {
                tlist.add(n);
            }
        }
        return tlist;
    }
    /**
     * 新增bom模型
     *
     * @param bomCost bom模型
     * @return 结果
     */
    @Override
    public int insertBomCost(BomCost bomCost)
    {
        bomCost.setCreateTime(DateUtils.getNowDate());
        return bomCostMapper.insertBomCost(bomCost);
    }

    /**
     * 修改bom模型
     *
     * @param bomCost bom模型
     * @return 结果
     */
    @Override
    public int updateBomCost(BomCost bomCost)
    {

        bomCost.setUpdateTime(DateUtils.getNowDate());
        int i = bomCostMapper.updateBomCost(bomCost);
        //修改root下的所有该物料价格 可能会有多个该半成品
        BomCost pb = new BomCost();
        pb.setPartId(bomCost.getPartId());
        pb.setBomVar(bomCost.getBomVar());
        pb.setRootCode(bomCost.getRootCode());
        List<BomCost> bomCosts = bomCostMapper.selectBomCostList(pb);
        for (BomCost cost : bomCosts) {
            if("0".equals(cost.getType())){
                if(null != bomCost.getWorkFee()){
                    cost.setWorkFee(bomCost.getWorkFee());
                }
                if(null != bomCost.getGasFee()){
                    cost.setGasFee(bomCost.getGasFee());
                }
                if(null != bomCost.getElecFee()){
                    cost.setElecFee(bomCost.getElecFee());
                }
                if(null != bomCost.getMakeFee()){
                    cost.setMakeFee(bomCost.getMakeFee());
                }
                int i1 = bomCostMapper.updateBomCost(bomCost);
            }else{
                if(null!=bomCost.getMarketPrice()){
                    cost.setMarketPrice(bomCost.getMarketPrice());
                }
            }
        }
        //更新bom价格
        updateBomCostPrice(bomCost);
        return i;
    }

    /**
     * @author: Liujiaji
     * @date: 2023/1/2 10:13
     * @description: TODO 修改单个bom价格,只修改价格
     * @param: [bomCost]
     * @return: void
     **/
    public void updateBomCostPrice(BomCost bomCost){
        //找到根节点
        BomCost bomCost1 = new BomCost();
        bomCost1.setRootCode(bomCost.getRootCode());
        bomCost1.setPartId(bomCost.getRootCode());
        bomCost1.setParentId("root");
        bomCost1.setBomVar(bomCost.getBomVar());
        List<BomCost> bomCosts = bomCostMapper.selectBomCostList(bomCost1);
        //标准
        BigDecimal sy = new BigDecimal("0");
        //市场及测算
        BigDecimal te = new BigDecimal("0");
        //人工
        BigDecimal rg = new BigDecimal("0");
        if(!bomCosts.isEmpty()) {
            BomCost bomCost2 = bomCosts.get(0);
            //将人工费相加
            if(null != bomCost2.getWorkFee()){
                rg = rg.add(bomCost2.getWorkFee());
            }
            if(null != bomCost2.getGasFee()){
                rg = rg.add(bomCost2.getGasFee());
            }
            if(null != bomCost2.getElecFee()){
                rg = rg.add(bomCost2.getElecFee());
            }
            if(null != bomCost2.getMakeFee()){
                rg = rg.add(bomCost2.getMakeFee());
            }
            //获取子节点的价格并加人工价格
            Map<String, BigDecimal> resultMap = sumBomFee(bomCost2);
            //材料价格
            BigDecimal sy1 = resultMap.get("sy");
            bomCost2.setPrice(sy1);
            sy = sy.add(rg).add(sy1);
            //市场价格
            BigDecimal te1 = resultMap.get("te");
            bomCost2.setMarketPrice(te1);
            te = te.add(rg).add(te1);
            //成品价格  = 标准成本+人工
            bomCost2.setProductPrice(sy);
            //标准成本 = (人工+材料价格)*数量
            BigDecimal syCost = sy.multiply(new BigDecimal(bomCost2.getCounts()));
            bomCost2.setStTotalFee(syCost);
            //市场成本 = (人工+市场价格)*数量
            BigDecimal teCost = te.multiply(new BigDecimal(bomCost2.getCounts()));
            bomCost2.setTotalFee(teCost);
            //信息更新
            bomCostMapper.updateBomCost(bomCost2);
        }
    }

    public Map<String, BigDecimal> sumBomFee(BomCost bomCost){
        //查找该节点下的子节点
        String partId = bomCost.getPartId();
        String bomVar = bomCost.getBomVar();
        String bomName = bomCost.getBomName();
        String rootCode = bomCost.getRootCode();
        String seqnum = bomCost.getSeqnum();
        BomCost bomCost1 = new BomCost();
        bomCost1.setParentId(partId);
        bomCost1.setBomVar(bomVar);
        bomCost1.setBomName(bomName);
        bomCost1.setRootCode(rootCode);
        bomCost1.setSeqnum(seqnum);
        List<BomCost> bomCosts = bomCostMapper.selectBomCostList(bomCost1);
        BigDecimal sy = new BigDecimal("0");
        BigDecimal te = new BigDecimal("0");
        for (BomCost cost : bomCosts) {
            BigDecimal sy1 = new BigDecimal("0");
            BigDecimal te1 = new BigDecimal("0");
            //判断该节点是产品还是原料
            String type = cost.getType();
            if("0".equals(type)){
                //原料 价格*数量 = 成本
                //标准成本
                if(null != cost.getPrice()){
                    BigDecimal total = cost.getPrice().multiply(new BigDecimal(cost.getCounts()));
                    cost.setStTotalFee(total);
                    cost.setTotalFee(total);
                    sy1 = total;
                    te1 = total;
                }
                //市场成本
                if(null != cost.getMarketPrice()){
                    BigDecimal total = cost.getMarketPrice().multiply(new BigDecimal(cost.getCounts()));
                    cost.setTotalFee(total);
                    te1 = total;
                }
                sy = sy.add(sy1);
                te = te.add(te1);
                bomCostMapper.updateBomCost(cost);
            }else{
                //产品
                //人工费用合计
                BigDecimal rg = new BigDecimal("0");
                if(null != cost.getWorkFee()){
                    rg = rg.add(cost.getWorkFee());
                }
                if(null != cost.getGasFee()){
                    rg = rg.add(cost.getGasFee());
                }
                if(null != cost.getElecFee()){
                    rg = rg.add(cost.getElecFee());
                }
                if(null != cost.getMakeFee()){
                    rg = rg.add(cost.getMakeFee());
                }
                Map<String, BigDecimal> resultMap = sumBomFee(cost);
                //材料价格 = 返回的结果价格
                BigDecimal sy2 = resultMap.get("sy");
                cost.setPrice(sy2);
                //市场价格 = 返回的价格
                BigDecimal te2 = resultMap.get("te");
                cost.setMarketPrice(te2);
                //成品价格 = 材料价格+人工
                BigDecimal cptotal = sy2.add(rg);
                cost.setProductPrice(cptotal);
                //标准成本 = 成品价格*数量
                cost.setStTotalFee(cptotal.multiply(new BigDecimal(cost.getCounts())));
                //市场成本 = (市场价格+人工)*数量
                BigDecimal sccb = te2.add(rg);
                cost.setTotalFee(sccb.multiply(new BigDecimal(cost.getCounts())));
                //更新信息
                bomCostMapper.updateBomCost(cost);
                sy = sy.add(cost.getStTotalFee());
                te = te.add(cost.getTotalFee());
            }
        }
        //判断该节点是成品还是原料
        Map<String,BigDecimal> resultMap = new HashMap<>();
        resultMap.put("sy",sy);
        resultMap.put("te",te);
        return resultMap;
    }


    /**
     * 批量删除bom模型
     *
     * @param ids 需要删除的bom模型主键
     * @return 结果
     */
    @Override
    public int deleteBomCostByIds(String[] ids)
    {
        return bomCostMapper.deleteBomCostByIds(ids);
    }

    /**
     * 删除bom模型信息
     *
     * @param id bom模型主键
     * @return 结果
     */
    @Override
    public int deleteBomCostById(String id)
    {
        return bomCostMapper.deleteBomCostById(id);
    }
}
